<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>经验反馈</el-breadcrumb-item>
      <el-breadcrumb-item>经验反馈管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入搜索关键字"
            v-model="queryInfo.query"
            class="input-with-select"
            clearable
            @keyup.enter.native="getFeedback"
            size="mini"
          >
            <el-button slot="append" icon="el-icon-search" @click="getFeedback" size="mini"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="exportExcel" size="mini">导出EXCEL</el-button>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" size="mini" @click="downloadTemplate">下载EXCEL模板</el-button>
        </el-col>
        <el-col :span="4">
          <el-upload
            ref="uploadRef"
            :action="uploadURL"
            :on-remove="handleRemove"
            :limit="1"
            :file-list="fileList"
            :on-exceed="exceedLimit"
            :headers="uploadHeader"
            name="feedbackExcel"
            accept=".xlsx"
            :on-success="uploadSuccess"
          >
            <el-button size="mini" type="primary">上传excel</el-button>

            <!-- <div slot="tip" class="el-upload__tip">只能上传excel文件，且不超过5MB</div> -->
          </el-upload>
        </el-col>
        <el-col :span="2"><p></p></el-col>
        <el-col :span="3">
          <el-button type="primary" @click="addBtnClick" size="mini">添加经验反馈</el-button>
        </el-col>
      </el-row>

      <!-- 读取excel成功后的显示操作区域 -->
      <el-dialog title="批量上传经验反馈" :visible.sync="dialogVisible" :fullscreen="true" @close="dialogClose">
        <div>
          <div class="tips">共读取了x条经验反馈，其中数据库中已经存在n条</div>
          <div id="btns">
            <div class="btnContainer"><el-button type="primary" @click="confirmUpload" size="mini">确认上传数据</el-button></div>
            <div class="btnContainer"><el-button type="primary" @click="cancelUpload" size="mini">取消</el-button></div>
          </div>
          <el-table :data="uploadFeedbacks" style="width: 100%" size="mini" border stripe>
            <el-table-column type="expand" width="30">
              <template slot-scope="scope">
                <el-row :gutter="2">
                  <el-col :span="7">{{ scope.row.detail }}</el-col>
                  <el-col :span="7">{{ scope.row.reason }}</el-col>
                  <el-col :span="7">{{ scope.row.measure }}</el-col>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="50"> </el-table-column>
            <el-table-column prop="outage" label="大修" width="60"> </el-table-column>
            <el-table-column prop="team" label="项目名称" width="70"> </el-table-column>

            <el-table-column label="事件标题">
              <template slot-scope="scope">
                {{ scope.row.title | shortStr(40) }}
              </template>
            </el-table-column>

            <el-table-column label="事件描述">
              <template slot-scope="scope">
                {{ scope.row.detail | shortStr(40) }}
              </template>
            </el-table-column>

            <el-table-column label="原因分析">
              <template slot-scope="scope">
                {{ scope.row.reason | shortStr(40) }}
              </template>
            </el-table-column>
            <el-table-column label="反馈措施">
              <template slot-scope="scope">
                {{ scope.row.measure | shortStr(40) }}
              </template>
            </el-table-column>
            <el-table-column prop="occurDate" label="发生日期" width="100"> </el-table-column>
            <el-table-column label="录入人" width="80" prop="create_user"> </el-table-column>
            <el-table-column label="是否重复" width="80" prop="is_repeat"> </el-table-column>
          </el-table>
        </div>
      </el-dialog>
      <div class="messageContainer" v-show="dialogVisible"></div>

      <!-- 经验反馈的表格展示区域 -->
      <el-table :data="feedbackList" style="width: 100%" size="mini" border stripe>
        <el-table-column type="expand" width="30">
          <template slot-scope="scope">
            <el-row :gutter="5">
              <el-col :span="7">{{ scope.row.detail }}</el-col>
              <el-col :span="7">{{ scope.row.reason }}</el-col>
              <el-col :span="7">{{ scope.row.measure }}</el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="50"> </el-table-column>
        <el-table-column prop="outage" label="大修" width="60"> </el-table-column>
        <el-table-column prop="team" label="项目名称" width="70"> </el-table-column>

        <el-table-column label="事件标题">
          <template slot-scope="scope">
            {{ scope.row.title | shortStr(40) }}
          </template>
        </el-table-column>

        <el-table-column label="事件描述">
          <template slot-scope="scope">
            {{ scope.row.detail | shortStr(40) }}
          </template>
        </el-table-column>

        <el-table-column label="原因分析">
          <template slot-scope="scope">
            {{ scope.row.reason | shortStr(40) }}
          </template>
        </el-table-column>
        <el-table-column label="反馈措施">
          <template slot-scope="scope">
            {{ scope.row.measure | shortStr(40) }}
          </template>
        </el-table-column>
        <el-table-column prop="occurDate" label="发生日期" width="100"> </el-table-column>
        <el-table-column label="录入人" width="80">
          <template slot-scope="scope">
            {{ scope.row.create_user }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="130">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="EditBtnClick(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteFeedbackById(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[20, 30, 50, 100]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        size="mini"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        query: '',
        pagesize: 20,
        pagenum: 1
      },
      feedbackList: [],
      total: 20,
      uploadHeader: {
        Authorization: window.sessionStorage.getItem('token')
      },
      uploadURL: this.serverURL + '/api/feedback/uploadexcel/',
      fileList: [],
      // 读取excel成功后显示对话框
      dialogVisible: false,
      uploadFeedbacks: []
    }
  },
  created() {
    this.getFeedback()
  },
  methods: {
    //   获取经验反馈列表
    async getFeedback() {
      const { data: res } = await this.$http.get('feedback/getfeedback/', { params: this.queryInfo })
      if (res.meta.status === 200) {
        this.feedbackList = res.data.page_feedbacks
        this.total = res.data.total
        this.queryInfo.pagenum = res.data.pagenum
        this.$message.success('获取经验反馈数据成功')
      } else if (res.meta.status === 201) {
        this.feedbackList = []
        this.queryInfo.pagenum = 1
        this.total = 0
        this.$message.info('未查询到相关数据')
      } else {
        this.feedbackList = []
        this.queryInfo.pagenum = 1
        this.total = 0
        this.$message.info('查询过程中发生错误！')
      }
    },
    // 添加经验反馈按钮
    addBtnClick() {
      this.$router.push('/addfeedback')
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getFeedback()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getFeedback()
    },
    // 根据id删除经验反馈
    async deleteFeedbackById(feedback_id) {
      const confirmResult = await this.$confirm('此操作将永久删除该经验反馈, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      if (confirmResult === 'confirm') {
        const { data: res } = await this.$http.delete(`feedback/deletefeedback/${feedback_id}/`)
        if (res.meta.status !== 200) {
          return this.$message.error('经验反馈删除失败！')
        }
        this.$message.success(res.meta.message)
        this.getFeedback()
      }
    },
    // 点击编辑按钮
    EditBtnClick(feedback_id) {
      this.$router.push(`/editfeedback?id=${feedback_id}`)
    },
    // 导出Excel
    async exportExcel() {
      const { data: res } = await this.$http.get('feedback/exportoexcel/', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error('经验反馈导出到excel失败')
      }
      window.open(res.data.excel_url)
      this.$message.success('经验反馈导出到excel成功！')
    },
    // 下载经验反馈模板
    downloadTemplate() {
      window.open(this.serverURL + '/media/excel/经验反馈导入模板.xlsx')
    },
    // 删除上传的文件
    handleRemove() {
      this.uploadFeedbacks = []
      this.dialogVisible = false
      this.$refs.uploadRef.clearFiles()
    },
    // 超过上传文件限制处理函数
    exceedLimit() {
      return this.$message.error('只能上传一个文件')
    },
    // 上传成功后的处理函数
    uploadSuccess(res, file, fileList) {
      // console.log(res)
      if (res.meta.status === 200) {
        this.uploadFeedbacks = res.data.feedbacks
        this.$message.success('读取excel成功！')
        this.dialogVisible = true
      }
    },
    // 确认上传经验反馈按钮
    async confirmUpload() {
      const { data: res } = await this.$http.post('feedback/savefeedbacks/', this.uploadFeedbacks)
      console.log(res)
      this.$refs.uploadRef.clearFiles()
      this.dialogVisible = false
      this.uploadFeedbacks = []
      if (res.meta.status === 200) {
        this.$message.success(`成功保存${res.data.saved}条经验反馈，数据库中已经存在的${res.data.ignored}条已经自动被忽略`)
        this.getFeedback()
        return
      }
      return this.$message.error('上传发生未知错误，请联系管理员。')
    },
    // 取消上传按钮
    cancelUpload() {
      this.uploadFeedbacks = []
      this.dialogVisible = false
      this.$refs.uploadRef.clearFiles()
      this.$message.info('已经取消上传')
    },
    // 上传经验反馈对话框关闭响应函数
    dialogClose() {
      this.uploadFeedbacks = []
      this.dialogVisible = false
      this.$refs.uploadRef.clearFiles()
    }
  },
  filters: {
    shortStr(value, maxlength) {
      if (value.length > maxlength) {
        return value.substring(0, maxlength) + '...'
      }
      return value
    }
  }
}
</script>

<style lang="less" scoped>
.tips {
  color: #555;
}

#btns {
  display: flex;
  justify-content: left;
  margin: 5px;
  .btnContainer {
    margin: 10px 20px;
  }
}

.el-table__expanded-cell > div {
  background-color: rgba(167, 252, 181, 0.418) !important;
  padding: 10px;
}
</style>
